/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.songlanyun.common.xss;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * XSS过滤
 *
 * @author Mark sunlightcs@gmail.com
 */
public class XssFilter implements Filter {

    // XSS处理Map
    private static Map<String, String> xssMap = new LinkedHashMap<String, String>();

    @Override
    public void init(FilterConfig config) throws ServletException {
        // 含有脚本： script
        xssMap.put("[s|S][c|C][r|R][i|C][p|P][t|T]", "");
        // 含有脚本 javascript
        xssMap.put("[\\\"\\\'][\\s]*[j|J][a|A][v|V][a|A][s|S][c|C][r|R][i|I][p|P][t|T]:(.*)[\\\"\\\']", "\"\"");
        // 含有函数： eval
        xssMap.put("[e|E][v|V][a|A][l|L]\\((.*)\\)", "");
        // 含有符号 <
        xssMap.put("<", "");
        // 含有符号 >
        xssMap.put(">", "");
        // 含有符号 (
        xssMap.put("\\(", "(");
        // 含有符号 )
        xssMap.put("\\)", ")");
        // 含有符号 '
        xssMap.put("'", "'");
        // 含有符号 "
        xssMap.put("\"", "\"");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (handleExcludeURL(req, resp)) {
            chain.doFilter(request, response);
            return;
        }

        // 构造HttpRequestWrapper对象处理XSS
        XssHttpRequestWrapper httpReqWarp = new XssHttpRequestWrapper((HttpServletRequest) request, xssMap);
//		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
//				(HttpServletRequest) request);
        chain.doFilter(httpReqWarp, response);
    }

    @Override
    public void destroy() {
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
//        String url = request.getServletPath();
        String method = request.getMethod().toUpperCase();
        // GET DELETE 不过滤
        if (method == null || method.matches("GET") || method.matches("DELETE")) {
            return true;
        }
        return false;
    }

}
